import React from 'react';
import {Spin, Card, Button, Table, Row, Col} from 'antd';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PropTypes from 'prop-types';
import {transportType, partOrderPriceTerms, paymentType, currency} from '../Enum';
import routes from './routes';
import {DATETIME_FORMAT, TABLE, FORM_OPTIONS} from '../constants';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {getDetail, confirmData} from './api';
import {injectIntl} from './intl';
import FileUpload from './FileUpload';
import styles from './style.css';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {confirmValidator} from './validator';
import Return from '../common/Return';
const {Description} = DescriptionList;
const EMPTY_ARRAY = [];

class ConfirmPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        details: [],
        partSaleOrder: {},
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.details.map(d => Object.assign({}, d, {
                            order: res.data.details.findIndex(x => x.partId === d.partId) + 1,
                        })),
                        partSaleOrder: res.data.partSaleOrder
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onSubmit = () => {
        this.setState({
            loading: true
        });
        const {data} = this.state;
        const condition = {
            rowVersion: data.rowVersion,
            attachments: (data.attachments || []).map(v => ({
                fileId: v.fileId,
                fileName: v.fileName
            }))
        };
        const isValid = confirmValidator(condition);
        if(!isValid) {
            this.setState({
                isValidate: true,
                loading: false
            });
            return;
        }
        confirmData(data.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    render() {
        const {data, partSaleOrder, loading} = this.state;
        const confirmable = !hasPermissions(PERMISSION.confirm, this.props.permissions);
        const {formatMessage} = this.props.intl;
        let totalAmount = 0;
        let totalQuantity = 0;
        if(this.state.details)
            this.state.details.forEach(d => {
                totalAmount += (d.amount);
                totalQuantity += (d.quantity);
            });
        const colums = [{
            title: formatMessage({
                id: 'detailPanel.column.order',
                defaultMessage: '序号'
            }),
            dataIndex: 'order',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            width: 200,
            dataIndex: 'partName',
            render: text => <div title={text} className={styles.partBtn}>{text}</div>
        }, {
            title: formatMessage({
                id: 'detailPanel.column.quantity',
                defaultMessage: '订购数量'
            }),
            dataIndex: 'quantity'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.amount',
                defaultMessage: '金额'
            }),
            dataIndex: 'amount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.newPartCode',
                defaultMessage: '被替换件编号'
            }),
            dataIndex: 'newPartCode'
        }];

        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={6}>{
                            formatMessage({
                                id: 'detailPanel.card.partOtherOrder',
                                defaultMessage: '订单信息'
                            })
                        }</Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.dealerCode',
                                defaultMessage: '总代号'
                            })}>{partSaleOrder.dealerCode}
                            </Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.submitTime',
                                defaultMessage: '提报日期'
                            })}>{formatDateTime(partSaleOrder.submitTime, DATETIME_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.country',
                                defaultMessage: '国家/地区'
                            })}>{partSaleOrder.country}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.code',
                                defaultMessage: '备件订单号'
                            })}>{partSaleOrder.code}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.partOrderType',
                                defaultMessage: '订单类型'
                            })}>{partSaleOrder.partOrderTypeName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.paymentType',
                                defaultMessage: '付款方式'
                            })}>{conventEnumValueToString(paymentType, partSaleOrder.paymentType)}</Description>
                            <Description term={formatMessage({
                                id: 'detail.operation.customerOrderCode',
                                defaultMessage: '客户订单号'
                            })}>{partSaleOrder.customerOrderCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedPerson',
                                defaultMessage: '收货联系人'
                            })}>{partSaleOrder.receivedPerson}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.partOrderPriceTerms',
                                defaultMessage: '价格条款'
                            })}>{conventEnumValueToString(partOrderPriceTerms, partSaleOrder.partOrderPriceTerms)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedPersonPhone',
                                defaultMessage: '联系电话'
                            })}>{partSaleOrder.receivedPersonPhone}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.carier',
                                defaultMessage: '指定货代'
                            })}>{partSaleOrder.carier}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.transportType',
                                defaultMessage: '运输方式'
                            })}>{conventEnumValueToString(transportType, partSaleOrder.transportType)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedPort',
                                defaultMessage: '目的港口'
                            })}>{partSaleOrder.receivedPort}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, partSaleOrder.currency)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.shipmentPort',
                                defaultMessage: '发运港口'
                            })}>{partSaleOrder.shipmentPort}</Description>
                        </DescriptionList>
                        <DescriptionList col="1" className={styles.detailDescriptionList}>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.receivedAddress',
                                defaultMessage: '收货地址'
                            })}>{partSaleOrder.receivedAddress}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.remark',
                                defaultMessage: '备注'
                            })}>{partSaleOrder.remark}</Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.other',
                            defaultMessage: '收款信息'
                        })}>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.bankAccount',
                                defaultMessage: '银行账号'
                            })}>{data.bankAccount}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.operation.comment',
                                defaultMessage: '意见'
                            })}>{data.comment}</Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'confirmPanel.table.details',
                            defaultMessage: '备件信息'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="id"
                                pagination={false}
                                dataSource={this.state.details}
                                footer={() => <DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalAmount',
                                        defaultMessage: '总金额'
                                    })}>{formatAmount(totalAmount)}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalQuantity',
                                        defaultMessage: '总数量'
                                    })}>{totalQuantity}
                                    </Description>
                                </DescriptionList>}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card title={formatMessage({
                        id: 'reportPanel.title.files',
                        defaultMessage: '附件清单'
                    })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FileUpload onChange={this.onChangeUpload}
                                    onRemove={this.removeFilePath}
                                    fileList={data.attachments || EMPTY_ARRAY}/>
                            </Col>
                        </Row>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!confirmable}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.confirm',
                                defaultMessage: '确认'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickReturnBtn}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

ConfirmPanel.propTypes = {
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object
};

import {connect} from 'react-redux';
import {tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ConfirmPanel));
